package solutionsdemo;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 黎鹤舞
 * Date: 2024-01-27
 * Time: 14:12
 */

/**
 * 对称二叉树
 */
public class IsSymmetric {
    public boolean isSymmetric(TreeNode root) {
        if(root == null) {
            return true;
        }
        return isSymmetricChild(root.left,root.right);
    }
    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        //要判断对称先判断结构
        if((leftTree == null && rightTree != null) || (leftTree != null && rightTree == null) ) {
            return false;
        }
        if(leftTree == null && rightTree == null) {
            return true;
        }
        //如果结构相同，则判断左右子树的值是否对称
        if(leftTree.val != rightTree.val) {
            return false;
        }
        return isSymmetricChild(leftTree.left,rightTree.right)
                && isSymmetricChild(leftTree.right,  rightTree.left);
    }

    //方法一:将二叉树的左子树进行反转，判断是否和二叉树的右子树相同，如果相同则为对称二叉树
//    public TreeNode invertTree(TreeNode root) {
//        if(root == null) {
//            return null;
//        }
//        TreeNode temp = root.left;
//        root.left = root.right;
//        root.right = temp;
//        invertTree(root.left);
//        invertTree(root.right);
//        return root;
//    }
//    //判断二叉树是否相同
//    public boolean isSamTree(TreeNode left,TreeNode right) {
//        if( (left == null && right != null) || (left != null && right == null)) {
//            return false;
//        }
//        if(left == null && right == null) {
//            return true;
//        }
//        if(left.val != right.val) {
//            return false;
//        }
//        return isSamTree(left.left,right.left) && isSamTree(left.right,right.right);
//
//    }
//    public boolean isSymmetric(TreeNode root) {
//        if(root == null) {
//            return true;
//        }
//        root.left = invertTree(root.left);
//        if(isSamTree(root.left,root.right)) {
//            return true;
//        }
//        return false;
//
//    }
}
